<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }
    public function render($request, Throwable $exception)
    {
        $e = $exception;
        if ($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
            return response()->view('errors.404', [], 404);
        }
        if ($e instanceof APIErrorException) {
            $code = $e->isLogin() ? 401 : 500;
            return new JsonResponse(['data' => new \StdClass(), 'code' => $code, 'msg' => $e->getMessage()],$code);
        }
        if($e instanceof ValidationException){
            $msg = [];
            foreach ($e->errors() as $errors){
                $msg = array_merge($msg,$errors);
            }
            if($msg){
                $msg = implode("\n",$msg);
            }else{
                $msg = $e->getMessage();
            }
            return new JsonResponse(['data' => new \StdClass(), 'code' => 500, 'msg' => $msg],500);
        }

        if (Str::startsWith($request->getPathInfo(), '/api')) {
            Log::error($request->getPathInfo() . ':' . $exception->getMessage() . PHP_EOL . $exception->getTraceAsString());
            return new JsonResponse(['data' => new \StdClass(), 'code' => 500, 'msg' => '系統繁忙，請稍後重試'],500);
        }

        return parent::render($request, $exception);
    }
}
